package com.hongshan.wallet.core.main

import android.Manifest
import android.app.Activity
import android.content.Intent
import android.content.pm.ActivityInfo
import android.os.Bundle
import android.support.v7.app.AlertDialog
import android.support.v7.app.AppCompatActivity
import com.hongshan.wallet.BuildConfig
import com.hongshan.wallet.Constant
import com.hongshan.wallet.MyApplication
import com.hongshan.wallet.R
import com.hongshan.wallet.bean.UserBean
import com.hongshan.wallet.core.comm.GuideActivity
import com.hongshan.wallet.router.RouterIndex
import com.hongshan.wallet.router.go
import com.hongshan.wallet.toast
import com.hongshan.wallet.util.NotificationUtils
import com.jaeger.library.StatusBarUtil
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import pub.devrel.easypermissions.AppSettingsDialog
import pub.devrel.easypermissions.EasyPermissions


/**
 * Copyright Qiandai Ltd.
 * Copyright (c) 2019
 * All rights reserved
 *
 * @project  : Wallet
 * @package  : com.example.wallet.core.main
 * @author   : Administrator
 * @data     : 2019/3/18
 * @email    : zhangxx@baihang-china.com
 */
class SplashActivity : AppCompatActivity(), EasyPermissions.PermissionCallbacks {

    val perms = arrayOf(Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE)
    var shouldGuide = MyApplication.sp.getString(Constant.SP.SP_KEY_LAST_RUN_VERSION, null) != BuildConfig.VERSION_NAME
    var canGoMain = false

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;
        setContentView(R.layout.activity_spalsh)
        StatusBarUtil.setColor(this, resources.getColor(R.color.transparent_white))
        if (EasyPermissions.hasPermissions(this, *perms)) {
            showGuide()
        } else {
            EasyPermissions.requestPermissions(this, "APP正常运行需要这些权限,否则会影响您的正常使用", PERMISSION_REQUEST_CODE, *perms)
        }
    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this)
        if (requestCode == AppSettingsDialog.DEFAULT_SETTINGS_REQ_CODE) {
            // Do something after user returned from app settings screen, like showing a Toast.
            toast("------")
        }
    }


    override fun onPermissionsGranted(requestCode: Int, perms: MutableList<String>) {
        if (EasyPermissions.hasPermissions(this, *this.perms)) {
            showGuide()
        }
    }

    fun showGuide() {
        if (shouldGuide) {
            go(
                RouterIndex.GUIDE, mapOf(
                    Constant.ROUTE_PARAMS_KEY.GUIDE_IMAGE to arrayListOf(
                        R.drawable.default1,
                        R.drawable.default2,
                        R.drawable.default3,
                        R.drawable.default4
                    )
                ),
                activity = this,
                requestCode = GuideActivity.REQUEST_CODE_GUIDE
            )
            MyApplication.sp.edit().putString(Constant.SP.SP_KEY_LAST_RUN_VERSION,BuildConfig.VERSION_NAME).apply()
            shouldGuide = false
        } else {
            next()
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == Activity.RESULT_OK && requestCode == GuideActivity.REQUEST_CODE_GUIDE) {
            next()
        }
    }

    private fun next() {
        if (!NotificationUtils.isNotificationEnabled(this)) {
            AlertDialog.Builder(this)
                .setTitle("通知")
                .setMessage("为了正常接单,我们需要显示通知的权限")
                .setPositiveButton("去设置") { dialog, _->
                    NotificationUtils.requestNotify(this)
                    canGoMain = true
                    dialog.dismiss()
                }
                .setNegativeButton("取消") { dialog, _->
                    dialog.dismiss()
                    goMain()
                }.show()
        } else{
            goMain()
        }
    }

    override fun onStart() {
        super.onStart()
        if (canGoMain) {
            goMain()
        }
    }

    private fun goMain() {
        GlobalScope.launch(Dispatchers.Main) {
            if (!BuildConfig.DEBUG) {
                delay(2500)
            } else {
                delay(500)
            }
            MyApplication.user = UserBean.load()
            if (MyApplication.user?.isEmpty() == false) {
                go(RouterIndex.MAIN)
            } else {
                go(RouterIndex.LOGIN)
            }
            finish()
        }
    }

    override fun onPermissionsDenied(requestCode: Int, perms: MutableList<String>) {
        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            AppSettingsDialog.Builder(this)
                .setRationale("您已经拒绝了权限提醒,如需要正常授权,请前往设置页面")
                .setNegativeButton("退出")
                .setPositiveButton("确定")
                .build()
                .show()
        } else {
            EasyPermissions.requestPermissions(
                this,
                "APP正常运行需要这些权限,否则会影响您的正常使用",
                PERMISSION_REQUEST_CODE,
                *perms.toTypedArray()
            )
        }
    }

    companion object {
        const val PERMISSION_REQUEST_CODE = 1000
    }
}